package com.cly.user.controller;

import com.cly.common.entity.result.Result;
import com.cly.common.entity.user.po.Address;
import com.cly.common.exception.CommonException;
import com.cly.common.util.ThreadLocalUtil;
import com.cly.user.service.AddressService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/address")
public class AddressController {

    @Autowired
    private AddressService addressService;

    /**
     * 添加地址
     * @param adress
     * @return
     */
    @PostMapping("/add")
    public Result addAdress(@RequestBody Address adress) {
        return addressService.addAdress(adress);
    }

    /**
     * 获取全部地址
     * @return
     */
    @GetMapping("/get")
    public Result<List<Address>> getAdressAll() {
        return addressService.getAddressAll();
    }

    /**
     * 根据地址id获取地址
     * @param id
     * @return
     */
    @GetMapping("/get/{id}")
    public Result getAdressById(@PathVariable("id") Long id) {
        Address address = addressService.getById(id);
        // 判断用户是否是该地址的拥有者
        if(address.getUserId() != ThreadLocalUtil.get()){
            throw new CommonException("该用户不存在该地址");
        }
        return Result.success(address);
    }

    /**
     * 修改地址
     * @param adress
     * @return
     */
    @PutMapping("/update")
    public Result updateAdress(@RequestBody Address adress) {
            return addressService.updateAddress(adress);
    }

    /**
     * 删除地址
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public Result deleteAdress(@PathVariable("id") Long id){
        try {
            addressService.removeById(id);
            return Result.success();
        } catch (Exception e) {
            throw new CommonException("地址删除失败",e);
        }

    }
}
